﻿using S7.Net;

namespace PLCComponent;

public class PlcConnectionUtil
{
    public static Plc CreateConnection(string cpuType,string ip, short rack, short slot)
    {
        CpuType type = CpuType.S71500;
        if (cpuType.Equals("S71500"))
        {
            type = CpuType.S71500;
        }

        if (cpuType.Equals("S71200"))
        {
            type = CpuType.S71200;
        }
        Plc plc = new Plc(type, ip, rack, slot);
        return plc;
    }

    public static async Task<Plc> OpenConnection(Plc plc,int timeout)
    {
        try
        {
            if (timeout == 0)
            {
                timeout = 3000;
            }
            Console.WriteLine("正在连接 PLC...");
            // 在 0.2 版本中，使用 ConnectAsync 并设置超时
            var connectTask = plc.OpenAsync();
            // 设置超时时间为 3 秒
            if (await Task.WhenAny(connectTask, Task.Delay(timeout)) != connectTask)
            {
                throw new TimeoutException("连接PLC超时...");
            }
            // 等待连接完成（如果未超时）
            await connectTask;
            if (plc.IsConnected)
            {
                Console.WriteLine("连接成功！");
                // 执行读写操作...
            }
        }
        catch (TimeoutException tex)
        {
            string msg = $"连接超时: {tex.Message}";
            throw new TimeoutException(msg);
        }
        catch (PlcException pex)
        {
            Console.WriteLine($"PLC 错误: {pex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"其他错误: {ex.Message}");
        }
        return plc;
    }

    public static async Task CloseConnection(Plc plc, int timeout)
    {
        try
        {
            if (plc.IsConnected)
            {
                plc.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}